/*
 * accept.c
 *
 *  Created on: 2009-5-28
 *      Author: root
 */
#include <sys/types.h>
#include <unistd.h>
#include"mysocket.h"
#include"msgtype.h"
#include <unistd.h>

int accept(int sockfd,struct sockaddr *cliaddr,int *addrlen){
	sockmsg retmsg;
	int rv,i;
	msg message;
	memset(&message,0,sizeof(msg));
	memset(&retmsg,0,sizeof(sockmsg));
	message.mtype=MSG_USR_ACCEPT;
	message.pid=getpid();
	message.sock=sockfd;
	for(i=1;i<MAXSOCKET;i++){
		if(sockbuf[i]==NULL)
			break;
	}
	if(i==MAXSOCKET){
		return -1;
	}
	sockbuf[i]=malloc(BUFLEN);
	sprintf(message.buf,"%d",i);
	message.buflen=strlen(message.buf);
	message.msgqid=processqid;
	if((rv=msgsnd(tcpipstackqid,&message,sizeof(msg)-sizeof(long),IPC_NOWAIT))<0){
		fprintf(stderr,"tcp/ip stack does not work!\n");
		return -1;
	}
	if((rv=msgrcv(processqid,&retmsg,sizeof(sockmsg)-sizeof(long),sockfd,0))<0){
		fprintf(stderr,"tcp/ip stack does not work!\n");
		return -1;
	}
	while(retmsg.ret==-2){
		usleep(500000);
		if((rv=msgsnd(tcpipstackqid,&message,sizeof(msg)-sizeof(long),IPC_NOWAIT))<0){
			fprintf(stderr,"tcp/ip stack does not work!\n");
			return -1;
		}
		if((rv=msgrcv(processqid,&retmsg,sizeof(sockmsg)-sizeof(long),sockfd,0))<0){
			fprintf(stderr,"tcp/ip stack does not work!\n");
			return -1;
		}
	}
	*cliaddr=retmsg.sock_addr;
	*addrlen=sizeof(retmsg.sock_addr);
	return retmsg.ret;
}
